package com.yc.mvc.web;

import com.yc.mvc.web.bean.User;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

// 被 RestController 修饰的控制, 内部方法默认情况下,返回json格式数据
// 请求转发和响应重定向要用 ModelAndView 实现
@RestController
@RequestMapping("abc")
public class HelloAction {

    @RequestMapping("hello")
    public String hello(){
        return "hello world!";
    }

    @RequestMapping("myinfo")
    public User myinfo(){
        User user = new User();
        user.setName("ly");
        user.setPwd("123");
        user.setAge(100);
        return user;
    }

    // 请求转发
    @RequestMapping("toIndexJsp")
    public ModelAndView toIndexJsp(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("forward:index.jsp");
        // 不写前缀,默认请求转发
        modelAndView.setViewName("/index.jsp");
        return modelAndView;
    }

    // 响应重定向
    @RequestMapping("goIndexJsp")
    // 接口注入 mav
    public ModelAndView goIndexJsp(ModelAndView mav){
        mav.setViewName("redirect:/index.jsp");
        return mav;
    }

    // 扩展了解: 请求转发与响应重定向的区别
    // abc/efg/show1.do
    // abc/efg/a/b/c/showAbc.do
    @RequestMapping("efg/**/show*.do")
    public User show(){
        User user = new User();
        user.setName("ls");
        user.setPwd("789");
        user.setAge(120);
        return user;
    }

    // abc/demo
    // RequestMethod.GET 默认
    @RequestMapping(path="demo", method = {RequestMethod.POST,RequestMethod.GET})
    public String demo(){
        return "demo";
    }
    // 等效于@RequestMapping(path="demo1", method = {RequestMethod.GET)
    @GetMapping(path="demo1")
    public String demo1(){
        return "demo1";
    }

    // 等效于@RequestMapping(path="demo2", method = {RequestMethod.POST)
    @PostMapping(path="demo2")
    public String demo2(){
        return "demo2";
    }

    // 格式 name  name=xxx name!=xxx
    @GetMapping(path="login", params = {"name","pwd!=123"})
    public String login(){
        return "login";
    }

    @GetMapping(path="demo30", headers = {
            "Accept",
            "Host=127.0.0.1:8080",
            "Cache-Control!='max-age=1'"})
    public String demo3(){
        return "demo3";
    }

    // consumes 限定请求体的内容格式
    @PostMapping(path="login.do",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public String login1(){
        return "login.do";
    }

    // consumes 设值响应体的内容格式
    @GetMapping(value="sayHello",
            produces = MediaType.TEXT_HTML_VALUE + ";charset=utf-8" )
    public String sayHello(){
        return "你好中国";
    }

}
